package se137.hrbust.hlgshopping137.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se137.hrbust.hlgshopping137.entity.PCTreeNode137;
import se137.hrbust.hlgshopping137.entity.PCategroy137;
import se137.hrbust.hlgshopping137.mapper.PCategroyMapper137;
import se137.hrbust.hlgshopping137.service.PCategroyService137;
import se137.hrbust.hlgshopping137.utils.SQLCommService137;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class PCategroyService137Impl implements PCategroyService137 {
    @Autowired
    PCategroyMapper137 mapper137;
    @Autowired
    SQLCommService137 sqlCommService;

    @Override
    public void addCategroy137(PCategroy137 categroy137) {
        mapper137.insert(categroy137);
    }

    @Override
    public void editCategroy137(PCategroy137 categroy137) {
        mapper137.updateById(categroy137);
    }

    @Override
    public void deleteCategroy137(int id) {
        mapper137.deleteById(id);
    }

    @Override
    public PCategroy137 findCategroyById137(int id) {

        return mapper137.selectById(id);
    }



    @Override
    public List<PCTreeNode137> getPCTreeList137(int pid) {
        List<PCTreeNode137> result=new ArrayList<>();

        PCTreeNode137 node=getNodeAndChildren(pid);
        result.add(node);
        return result;
    }

    public PCTreeNode137 getNodeAndChildren(int pcId){
        PCTreeNode137 result=new PCTreeNode137();
        String strSQL=String.format("select FPCateName137 from tb_pcategory137 where FPCatId137=%s",pcId);
        String strCateName=sqlCommService.getFieldStr(strSQL);
        result.setCateId(pcId);
        result.setCateName(strCateName);
        List<PCTreeNode137> children=new ArrayList<>();
        strSQL=String.format("select count(*) from tb_pcategory137 where FParentId137=%s",pcId);
        if(strSQL.equals("")||strSQL.equals("0")){
            children=null;
        }else{
            strSQL=String.format("select FPCatId137 from tb_pcategory137 where FParentId137=%s",pcId);
            List<Map<String,Object>> chirldrenList=sqlCommService.listResult(strSQL);
            for(int i=0;i<chirldrenList.size();i++){
                Map<String,Object> child=chirldrenList.get(i);
                int pcIdChild=Integer.parseInt(child.get("FPCatId137").toString());
                PCTreeNode137 childNode=getNodeAndChildren(pcIdChild);
                if(childNode!=null){
                    System.out.println("下级："+childNode.getCateName());
                    children.add(childNode);
                }
            }
            if(children.size()>0){
                result.setChildren(children);
            }
        }
        return result;
    }

}
